home *** CD-ROM | disk | FTP | other *** search
/ Aminet 51 / Aminet 51 (2002)(GTI - Schatztruhe)[!][Oct 2002].iso / Aminet / dev / gg / tcpbug.lha / tcpbug / ip / addr.c next >
Encoding:
C/C++ Source or Header  |  1996-07-04  |  1.6 KB  |  82 lines

  1. #include <stddef.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/socket.h>
  6. #include <netinet/in.h>
  7. #include <arpa/inet.h>
  8. #include <netdb.h>
  9.  
  10. #include "ip_misc.h"
  11.  
  12.  
  13. #define    Export
  14.  
  15.  
  16. /*
  17.  *  Fill in ADDR from HOST, SERVICE and PROTOCOL.
  18.  *  PROTOCOL can be tcp or udp.
  19.  *  Supplying a null pointer for HOST means use INADDR_ANY.
  20.  *  Supplying a null pointer for SERVICE, means use port 0, i.e. no port.
  21.  *
  22.  *  Returns negative on errors, zero or positive if everything ok.
  23.  */
  24. Export    int
  25. get_inaddr(struct sockaddr_in    * addr,
  26.        const char        * host,
  27.        const char        * service,
  28.        const char        * protocol)
  29. {
  30.     memset(addr, 0, sizeof *addr);
  31.     addr->sin_family = AF_INET;
  32.  
  33.     /*
  34.      *  Set host part of ADDR
  35.      */
  36.     if (host == NULL)
  37.     addr->sin_addr.s_addr = INADDR_ANY;
  38.     else
  39.     {
  40.     addr->sin_addr.s_addr = inet_addr(host);
  41.     if (addr->sin_addr.s_addr == (unsigned long)-1)
  42.     {
  43.         struct hostent    * hp;
  44.  
  45.         hp = gethostbyname(host);
  46.         if (hp == NULL)
  47.         return -1;
  48.         memcpy(&addr->sin_addr, hp->h_addr, hp->h_length);
  49.         addr->sin_family = hp->h_addrtype;
  50.     }
  51.     }
  52.  
  53.     /*
  54.      *  Set port part of ADDR
  55.      */
  56.     if (service == NULL)
  57.     addr->sin_port = htons(0);
  58.     else
  59.     {
  60.     char        * end;
  61.     long          portno;
  62.  
  63.     portno = strtol(service, &end, 10);
  64.     if (portno > 0  &&  portno <= 65535
  65.         &&  end != service  &&  *end == '\0')
  66.     {
  67.         addr->sin_port = htons(portno);
  68.     }
  69.     else
  70.     {
  71.         struct servent    * serv;
  72.  
  73.         serv = getservbyname(service, protocol);
  74.         if (serv == NULL)
  75.         return -1;
  76.         addr->sin_port = serv->s_port;
  77.     }
  78.     }
  79.  
  80.     return 0;
  81. }
  82.